package com.chatsocket.httpController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chatsocket.model.ChatContent;
import com.chatsocket.model.ChatVO;
import com.chatsocket.model.EchoBody;
import com.chatsocket.socketServlet.WebSocketServlet;
import com.chatsocket.util.Chat;
import com.chatsocket.util.ChatManager;
import com.chatsocket.util.Constant;
import com.chatsocket.util.Message;
import com.chatsocket.util.SendMsgBody;
import com.chatsocket.util.User;
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
	@RequestMapping("/login")
	@ResponseBody
	public Map<String,Object> login(@RequestParam(value="userCode",required=false)String userCode,HttpServletRequest request ){
		Map<String,Object> map=new HashMap<String, Object>();
		User user=Constant.getUser(userCode);
		if(user==null){
			map.put("status","fail");
			return map;
		}
		map.put("status", "SUCCESS");
		request.getSession().setAttribute(USER,user);
		map.put("wsBaseUrl", getWSBasePath(request));
		map.put("httpBaseUrl", getHttpBasePath(request));
		map.put("userId",user.getId());
		map.put("user",user);
		return map;
	}
	@RequestMapping("/sendMsg")
	@ResponseBody
	public Map<String,Object> sendMsg(HttpServletRequest request,SendMsgBody sendMsgBody){
		Map<String,Object> map=new HashMap<String,Object>();
		User user = (User)request.getSession().getAttribute(USER);
		sendMsgBody.setFrom(user.getId());
		sendMsgBody.setMsgTime(new Date());
		sendMsgBody.setMsgType("dialog");
		List<SendMsgBody> msgs = Constant.msgCacheMap.get(sendMsgBody.getTarget());
		if(msgs==null){
			msgs=new ArrayList<SendMsgBody>();
		}
		msgs.add(sendMsgBody);
		Constant.msgCacheMap.put(sendMsgBody.getTarget(),msgs);
		WebSocketServlet webSocketServlet = Constant.webSocketMap.get(sendMsgBody.getTarget()+"");
		if(webSocketServlet!=null){
			try {
				webSocketServlet.sendMessage("{\"staus\":\"hasMsg\",\"msgType\":\"dialog\"}");
			} catch (Exception e) {
				e.printStackTrace();
			}
		};
		return map;
	}
	@RequestMapping("/getMsg")
	@ResponseBody
	public Map<String,Object> getMsg(HttpServletRequest request){
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("status","SUCCESS");
		User user = (User) request.getSession().getAttribute(USER);
		Integer userType = user.getUserType();
//		List<SendMsgBody> bodys = Constant.msgCacheMap.get(user.getId());
		Map<Long, List<ChatContent>> map2 = Constant.chatContentCacheMap.get(userType+"_"+user.getId());
		map.put("data",map2);
		Constant.msgCacheMap.remove(user.getId());
		String str="";
		return map;
	}
	/**
	 * 获取联系人列表(从缓存)
	 * @param request
	 * @return
	 */
	@RequestMapping("/getLinkList")
	@ResponseBody
	public Map<String,Object> getLinkList(HttpServletRequest request){
		Map<String,Object> map=new HashMap<String,Object>();
		return map;
	}
	@RequestMapping("/sendMessage")
	@ResponseBody
	public Map<String,Object> sendMessage(HttpServletRequest request,ChatContent chatContent){
		Map<String,Object> map=new HashMap<String,Object>();
		User user = (User)request.getSession().getAttribute(USER);
		chatContent.setOrigin(user.getId());
		chatContent.setOriginType(user.getUserType());
		chatContent.setSendTime(new Date());
		Map<Long, List<ChatContent>> map2 = Constant.chatContentCacheMap.get(chatContent.getDestinationType()+"_"+chatContent.getDestination());
		if(map2==null){
			map2=new HashMap<Long, List<ChatContent>>();
		}
		List<ChatContent> contents = map2.get(chatContent.getChatId());
		if(contents==null){
			contents=new ArrayList<ChatContent>();
		}
		contents.add(chatContent);
		map2.put(chatContent.getChatId(),contents);
		Constant.chatContentCacheMap.put(chatContent.getDestinationType()+"_"+chatContent.getDestination(), map2);
		CopyOnWriteArraySet<WebSocketServlet> set = Constant.webSocketSetMap.get(chatContent.getDestinationType()+"_"+chatContent.getDestination());
		if(set!=null){
			for(WebSocketServlet webSocketServlet:set){
				if(webSocketServlet!=null){
					try {
						webSocketServlet.sendMessage(EchoBody.hasNewMsg());
					} catch (Exception e) {
						e.printStackTrace();
					}
				};
			}
		}
		return map;
	}
	@RequestMapping("/getMessage")
	@ResponseBody
	public Map<String,Object> getMessage(HttpServletRequest request,Long chatId){
		Map<String,Object> map=new HashMap<String,Object>();
		Long userId = getUserId(request);
		User user2 = getUser(request);
		Map<Long, List<ChatContent>> map2 = Constant.chatContentCacheMap.get(userId);
		Constant.chatContentCacheMap.remove(user2.getUserType()+"_"+user2.getId());
		map.put("data",map2);
		return map;
	}
	@RequestMapping("/getMessageByChatId")
	@ResponseBody
	public Map<String,Object> getMessageByChatId(HttpServletRequest request,Long chatId){
		Map<String,Object> map=new HashMap<String,Object>();
		Long userId = getUserId(request);
		User user2 = getUser(request);
		Map<Long, List<ChatContent>> map2 = Constant.chatContentCacheMap.get(user2.getUserType()+"_"+user2.getId());
//		Constant.chatContentCacheMap.remove(user2.getUserType()+"_"+user2.getId());
		if(map2!=null){
			map.put("data",map2.get(chatId));
			map2.remove(chatId);
		}
		return map;
	}
	@RequestMapping("/getChatVOsByUserId")
	@ResponseBody
	public Map<String,Object> getChatVOsByUserId(HttpServletRequest request){
		Map<String,Object> map=new HashMap<String,Object>();
		User user2 = getUser(request);
		List<ChatVO> chatVOs = Constant.getChatVOsByUserId(user2.getId());
		map.put("data",chatVOs);
		map.put("status","SUCCESS");
		return map;
	}
	/*
	 * ========================分界线============================================
	 */
	private final static String CHAT_MANAGER="_user_chat_manager";
	@RequestMapping("/loginA")
	@ResponseBody()
	public Map<String,Object> loginA(String userCode,HttpServletRequest request){
		User user=Constant.getUser(userCode);
		HttpSession session = request.getSession();
		session.setAttribute(USER,user);
		ChatManager chatManager=new ChatManager();
		chatManager.setCurrentUser(user);
		session.setAttribute(CHAT_MANAGER, chatManager);
		String sessionId=session.getId();
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("sessionId", sessionId);
		map.put("user",user);
		map.put("userRemark",user.getUserType()+"_"+user.getId());
		map.put("status", "SUCCESS");
		map.put("wsBaseUrl", getWSBasePath(request));
		map.put("httpBaseUrl", getHttpBasePath(request));
		return map;
	}
	/**
	 * 获取同一用户 别的session发送的消息
	 */
	@RequestMapping("/getMessageSelfA")
	@ResponseBody
	public Map<String,Object> getMessageSelfA(HttpServletRequest request){
		User user= (User)request.getSession().getAttribute(USER);
		String currentSessionId=request.getSession().getId();
		List<Message> msgs = Constant.USER_ORIGIN_MSG.get(user.getUserType()+"_"+user.getId());
		//要返回的数据
		List<Message> datas=new CopyOnWriteArrayList<Message>();
		if(msgs!=null&&msgs.size()>0){
			for(int i=0;i<msgs.size();i++){
				Message msg=msgs.get(i);
				List<String> sessionIds = msg.getOriginSessionIds();
				boolean flag = sessionIds.remove(currentSessionId);
				if(flag){
					datas.add(msg);
				}
				if(sessionIds.size()==0){
					msgs.remove(i);
				}
			}
		}
		Map<String,Object> map=new HashMap<>();
		map.put("data", datas);
		return map;
	}
	/**
	 * 获取别的用户所发送的信息
	 */
	@RequestMapping("/getMessageRecieveA")
	@ResponseBody
	public Map<String,Object> getMessageRecieveA(HttpServletRequest request,String userRemark){
		String currentSessionId=request.getSession().getId();
		User user = (User) request.getSession().getAttribute(USER);
		List<Message> msgs = Constant.USER_DESTINATION_MSG.get(user.getUserType()+"_"+user.getId());
		List<Message> datas=new CopyOnWriteArrayList<Message>(); 
		if(msgs!=null&&msgs.size()!=0){
			for(int i=0;i<msgs.size();i++){
				Message msg=msgs.get(i);
				List<String> sessionIds = msg.getDestinationSessionIds();
				boolean flag = sessionIds.remove(currentSessionId);
				if(flag){
					datas.add(msg);
				}
				if(sessionIds.size()==0){
					msgs.remove(i);
				}
			}
		}
		Map<String,Object> map=new HashMap<>();
		map.put("data", datas);
		return map;
	}
	/**
	 * 给某人发送消息
	 */
	@RequestMapping("/sendMessageA")
	@ResponseBody
	public Map<String,Object> sendMessageA(HttpServletRequest request,Message message){
		ChatManager chatManager = (ChatManager) request.getSession().getAttribute(CHAT_MANAGER);
		Chat chat = chatManager.getOrInitChatByThreadId(message.getDestination());
		chat.sendMessage(message.getContent(), 1,request.getSession().getId());
		return null;
	}

	@RequestMapping("/base64")
	@ResponseBody
	public Map<String, Object> base64(HttpServletRequest request,
			@RequestParam(required = false) Long userId,
			@RequestParam(required = false) String userName,
			@RequestParam(required = false) String timestamp,
			HttpServletResponse response) {
		try {
			ServletInputStream is = request.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(
					is,"UTF-8"));
			String line = null;
			StringBuffer sb=new StringBuffer();
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			System.out.println("sb:"+sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("userId:"+userId);
		System.out.println("userName:"+userName);
		System.out.println("timestamp:"+timestamp);
		System.out.println(request.getParameter("userName"));
		System.out.println(request.getRequestURI()+"||"+request.getRequestURL());
		String queryString = request.getQueryString();
		System.out.println("queryString:"+queryString);
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("status","SUCCESS");
		return map;
	}
}
